import _ from 'lodash'
import { errorSentry } from '@/lib/error-sentry'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { Modal, message } from 'ant-design-vue'
// 默认查询参数
interface Params {
  queryFormFilter: {
    [key: string]: any
  }
  queryFormOp: {
    [key: string]: QUERY_FORM_OP
  }
  page?: number
  limit?: number | null
  queryFormState?: any
  loading?: boolean
  fetchDataApi: (params: { page?: number | null; limit?: number | null; op: Params['queryFormOp']; filter: Params['queryFormFilter'] }) => Promise<{
    list: any[]
    total: number
  }>
  fetchDeleteApi?: (id: string) => Promise<boolean>
}
// ---------------------------- useQuery参数默认值 ----------------------------
const PAGE = 1
const LIMIT = 50
const LOADING = false

export const useQuery = (params: Params) => {
  const { queryFormFilter, queryFormOp, fetchDataApi, fetchDeleteApi, page = PAGE, limit = LIMIT, loading = LOADING } = params
  // 初始查询参数
  let initQueryFormParams = _.assign({}, queryFormFilter, { page, limit })

  // 查询表单form
  const queryForm = ref(_.cloneDeep(initQueryFormParams))
  // 表格加载loading
  const tableLoading = ref(loading)
  // 表格数据
  const tableData = ref<any>([])
  // 总数
  const total = ref(0)

  /**
   * 重置查询条件
   * */
  async function resetQuery(reload: boolean = true) {
    const { page, limit } = unref(queryForm)
    queryForm.value = _.assign({}, initQueryFormParams, { page, limit })
    if (reload) await queryData()
  }

  /**
   * 搜索
   * */
  async function onSearch() {
    queryForm.value.page = 1
    await queryData()
  }

  /**
   * 设置参数
   * */
  function setQuery(params: { [key: string]: any }, isConst: boolean = false) {
    isConst && (initQueryFormParams = _.assign({}, initQueryFormParams, params))
    queryForm.value = _.assign({}, queryForm.value, params)
  }

  /**
   * 查询数据
   * */
  async function queryData() {
    tableLoading.value = true
    try {
      const { page, limit, ...filter } = unref(queryForm)
      // TODO筛选filter中的有效字段
      //   const validFilter = _.pickBy(filter, (value) => value !== undefined && value !== '' && value !== null)
      //   const validOp = _.pick(queryFormOp, Object.keys(validFilter))

      const params = {
        op: queryFormOp,
        filter,
        page,
        limit
      }

      const queryResult = await fetchDataApi(params)
      tableData.value = queryResult.list
      total.value = queryResult.total
      // TODO合计当前页
    } catch (e) {
      message.error(e.msg)
      errorSentry.captureError(e)
    } finally {
      tableLoading.value = false
      let childDom = document.getElementsByClassName('ant-table-body')
      //- 滚动条置顶
      childDom[0].scrollTop = 0
    }
  }

  /**
   * 删除数据
   * */
  function deleteData(id: number, name: string): void
  function deleteData(id: number[]): void
  function deleteData(id: number | number[], name?: string): void {
    if (!fetchDeleteApi) throw new Error('请先添加fetchDeleteApi！')
    const modal_content = _.isArray(id) ? '确定要删除选中行吗?' : `确定要删除${name}吗?`
    const ids = _.isArray(id) ? id.join(',') : id
    Modal.confirm({
      title: '提示',
      content: modal_content,
      okText: '删除',
      okType: 'danger',
      async onOk() {
        try {
          await fetchDeleteApi(ids)
          message.success('删除成功')
          queryData()
        } catch (e) {
          message.error(e.msg)
          errorSentry.captureError(e)
        }
      },
      cancelText: '取消',
      onCancel() {}
    })
  }
  return {
    queryForm,
    queryFormOp,
    queryFormState: queryFormFilter,
    tableLoading,
    tableData,
    total,
    resetQuery,
    setQuery,
    onSearch,
    queryData,
    deleteData
  }
}
